package com.ruyuan.user.server.controller;

import com.ruyuan.common.web.model.WebResponse;
import com.ruyuan.gateway.sdk.facade.RuyuanGatewayFacade;
import com.ruyuan.user.server.controller.converter.WebJobConverter;
import com.ruyuan.user.server.controller.request.DelJobRequest;
import com.ruyuan.user.server.controller.request.SaveJobRequest;
import com.ruyuan.user.server.controller.request.SaveOrganizationRequest;
import com.ruyuan.user.server.controller.response.JobListVO;
import com.ruyuan.user.server.domain.model.Job;
import com.ruyuan.user.server.domain.model.Organization;
import com.ruyuan.user.server.domain.service.JobDomainService;
import com.ruyuan.user.server.domain.service.request.DelJobReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xx
 */
@Controller
@RequestMapping("/api/user/job")
public class JobController {

    @Autowired
    private WebJobConverter converter;

    @Autowired
    private JobDomainService jobDomainService;

    @Autowired
    private RuyuanGatewayFacade ruyuanGatewayFacade;

    @RequestMapping("/del")
    @ResponseBody
    public WebResponse<Boolean> delJob(@Validated @RequestBody DelJobRequest request, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return WebResponse.failWithMsg(bindingResult.getFieldError().getDefaultMessage());
        }
        DelJobReq req = new DelJobReq();
        req.setJobId(request.getJobId());
        req.setOperator(String.valueOf(ruyuanGatewayFacade.getCurrentUser().getUserId()));
        Boolean res = jobDomainService.delJob(req);
        return WebResponse.successWithData(res);
    }

    @RequestMapping("/saveJob")
    @ResponseBody
    public WebResponse<Long> saveJob(@Validated @RequestBody SaveJobRequest request, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return WebResponse.failWithMsg(bindingResult.getFieldError().getDefaultMessage());
        }
        Job job = converter.convertSaveJobRequestToJob(request);
        Long jobId = jobDomainService.saveJob(job);
        return WebResponse.successWithData(jobId);
    }

    @GetMapping("/queryByOrg")
    @ResponseBody
    public WebResponse<List<JobListVO>> queryJobByOrg(Long orgId) {
        if (orgId == null) {
            return WebResponse.successWithData(new ArrayList<>());
        }
        List<Job> jobs = jobDomainService.queryByOrgId(orgId);
        return WebResponse.successWithData(converter.convertToJobListVO(jobs));
    }

}
